function [ output subjectinfo ] = buildFrequencySet( subjectinfo, cfg )
%BUILDFREQUENCYSET Build a set of frequencydecompositions
%   Will transform an epoched dataset into frequency x time x trial x
%   electrode. Saves this data to disk and stores the info in the subject
%   information.

clc
output = [];
dataFolder = getpref('ECoG','Data');

for fn = fieldnames(subjectinfo.EpochData)'
    x = subjectinfo.EpochData.(cell2mat(fn));
    disp(x.name);
    if ~exist('cfg', 'var'), cfg = buildFrequencySet_defaultCfg(); end
    cfg.SubjectPrimaryPrefix = subjectinfo.PrimaryPrefix;
    cfg.EpochSetName = x.name;
    cfg.Input.EegSetFilename = x.dataFilename;
    cfg.Output.TfcDataFolder = [getpref('ECoG','Data') 'Timefreq\'];
    outputBFS = buildFrequencySet_Core(cfg);
%     EEG = pop_loadset('filename', x.dataFilename);
% 
%     for elecNr = 1:length(EEG.chanlocs);
%         
%         data.datecode = datecode;
%         data.epochs.name = x.name;
%         data.epochs.nrOfEpochsFound = x.nrOfEpochsFound;
%         data.channel = EEG.chanlocs(elecNr).labels;
%         disp(['Timefreqqing channel ''' data.channel '''...']);
%         [data.tf data.freqs data.times data.itcvals] = timefreq(squeeze(EEG.data(elecNr,:,:)), 512, 'ntimesout', 1000, 'freqs', [3 150], 'padratio', 2);
% 
% %         whos data tfc;
%         disp('Saving to file...')
%         filename = [dataFolder 'Timefreq\' subjectinfo.PrimaryPrefix ' ' data.channel ' ' x.name ' Timefreq data.mat'];
%         save(filename, '-v7.3', 'data');
%         subjectinfo.EpochData.(cell2mat(fn)).TfcData.(data.channel).Filename = filename;
%         subjectinfo.EpochData.(cell2mat(fn)).TfcData.(data.channel).Datecode = datecode;
% %         memory;
% 
%         clearvars -except fn x subjectinfo output dataFolder EEG tfc;
%     end
%     clearvars -except fn x subjectinfo output dataFolder;
    subjectinfo.EpochData.(cell2mat(fn)).TfcData = outputBFS.TfcData;
    
end
end